import { Body, Injectable, Post } from "@nestjs/common";
import { CreateUserRoleDto } from "./dto/create-user-role.dto";
import { UpdateUserRoleDto } from "./dto/update-user-role.dto";
import { ResultData } from "@/common/utils/result";
import { InjectRepository } from "@nestjs/typeorm";
import { UserRole } from "@/modules/system/user-role/entities/user-role.entity";
import { Repository } from "typeorm";

@Injectable()
export class UserRoleService {
    constructor(
        @InjectRepository(UserRole)
        private readonly userRoleRepository: Repository<UserRole>
    ) {
    }
    
    create(createUserRoleDto: CreateUserRoleDto) {
        return "This action adds a new userRole";
    }
    
    findAll() {
        return `This action returns all userRole`;
    }
    
    findOne(id: number) {
        return `This action returns a #${id} userRole`;
    }
    
    update(id: number, updateUserRoleDto: UpdateUserRoleDto) {
        return `This action updates a #${id} userRole`;
    }
    
    remove(id: number) {
        return `This action removes a #${id} userRole`;
    }
    
    //给用户添加角色
    async userAddRole({ roleIds, userId }) {
        console.log("userId",userId)
        // 删除所有再新增
        await this.userRoleRepository.delete({ userId });
        return ResultData.ok(
            await this.userRoleRepository.save(
                roleIds.map(v => ({ userId: userId, roleId: v }))
            )
        );
    }
    
    async getRoleIdByUserId({ userId }) {
        const res = await this.userRoleRepository.find(
            { where: { userId} }
        );
        return ResultData.ok(
            res.map(v => v.roleId)
        );
    }
    
  
}
